package com.lagou.server;

import com.lagou.client.module.Student;
import com.lagou.client.module.StudentMessage;
import com.lagou.client.module.UserMessage;

import java.io.IOException;

public class ServerView {

    private ServerInitClose serverInitClose;

    private ServerDao serverDao;

    public ServerView(ServerInitClose serverInitClose, ServerDao serverDao) {
        this.serverInitClose = serverInitClose;
        this.serverDao = serverDao;
    }

    /**
     * 管理员账号校验
     * @throws IOException
     * @throws ClassNotFoundException
     */
    public void serverReceive() throws IOException, ClassNotFoundException {

        UserMessage userMessage = (UserMessage) serverInitClose.getOis().readObject();
        System.out.println("服务端接收到客户端的管理员登录请求,请求数据为：" + userMessage);
        if(serverDao.serverManagerCheck(userMessage.getUser())){
            userMessage.setType("success");
        }else{
            userMessage.setType("fail");
        }
        serverInitClose.getOos().writeObject(userMessage);
        System.out.println("服务器发送校验结果成功！响应结果为：" + userMessage);

    }


    public void serverReceiveStd() throws IOException, ClassNotFoundException {

        while(true){
            StudentMessage studentMessage = (StudentMessage) serverInitClose.getOis().readObject();
            System.out.println("服务端接收到客户端请求为：" + studentMessage.getType() + "请求数据为：" + studentMessage);

            boolean oper = false;
            if("stdAdd".equals(studentMessage.getType())){
                oper = serverDao.stdAdd(studentMessage.getStudent());

            }else if("stdUpdate".equals(studentMessage.getType())){
                oper = serverDao.stdUpdate(studentMessage.getStudent());

            }else if("stdDel".equals(studentMessage.getType())){
                oper = serverDao.stdDel(studentMessage.getStudent());

            }else if("getStd".equals(studentMessage.getType())){
                Student student = serverDao.getStd(studentMessage.getStudent().getUsername());
                studentMessage.setStudent(student);
                oper = true;
            }

            if(oper){
                studentMessage.setType("success");
            }else{
                studentMessage.setType("fail");
            }
            serverInitClose.getOos().writeObject(studentMessage);
            System.out.println("服务器发送操作结果成功！响应结果是：" + studentMessage);
        }

    }
}
